﻿#region License

// Another free, open solution by folks who get it.
// Copyright © 2011 Business in Unison, Inc.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Collections.Generic;
using System.IO;

using Args;
using Args.Help;
using Args.Help.Formatters;

using Patterns.Tools.CodeGenerators;

namespace Patterns.Tools
{
	/// <summary>
	/// Defines the actual entry point to the program.
	/// </summary>
	public static class EntryPoint
	{
		private static readonly IDictionary<string, Func<Options, string>> _codeGenerators
			= new Dictionary<string, Func<Options, string>>(StringComparer.OrdinalIgnoreCase)
			{
				{ "AssemblyInfo", options => new AssemblyInfo{ Product = options.Product, Version = options.Version }.TransformText() }
			};

		public static void Run(string[] args)
		{
			IModelBindingDefinition<Options> optionsMap = Configuration.Configure<Options>();

			try
			{
				if (args == null || args.Length == 0) throw new InvalidOperationException("Nothing to do!");
				Options options = optionsMap.CreateAndBind(args);
				if (!string.IsNullOrEmpty(options.WorkingDirectory))
					Environment.CurrentDirectory = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, options.WorkingDirectory));
				if (options.CodeGen) RunCodeGenerator(options);
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
				var formatter = new ConsoleHelpFormatter(8000, 1, 3);
				formatter.WriteHelp(new HelpProvider().GenerateModelHelp(optionsMap), Console.Out);
			}
		}

		private static void RunCodeGenerator(Options options)
		{
			if (!_codeGenerators.ContainsKey(options.Target)) return;
			File.WriteAllText(options.Output, _codeGenerators[options.Target](options));
		}
	}
}